package com.moudle.app.fragment;

import android.app.AlertDialog;


import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.moudle.app.AppConfig;
import com.moudle.app.AppException;
import com.moudle.app.R;
import com.moudle.app.base.BaseFragMent;
import com.moudle.app.bean.Constant;
import com.moudle.app.bean.Entity;
import com.moudle.app.bean.SimpleBackPage;
import com.moudle.app.common.StringUtils;
import com.moudle.app.common.UIHelper;
import com.moudle.app.base.BaseActivity;
import com.moudle.app.explorer.HDExplorerActivity;

import java.io.Serializable;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.SaveListener;


/**
 * @Description 登陆模块
 * @Author Li Chao
 * @Date 2015/12/10 11:23
 */
public class LoginFragment extends BaseFragMent {
    private Button mBtnMessage;// 短信验证登陆
    private Button mBtnLogin;// 普通登陆
    private EditText mEtUsername;
    private EditText mEtPassword;
    private Button mBtnForPassword;// 忘记密码
    private TextView mTvRegister;
    private String mUsername;
    private String mPassword;
    private ImageButton mIbBack;// 回退按钮
    private LoginCodeFragment mLoginCodeFragment;
    private RegFragment mRegFragment;
    private ForgetPwdFragment mForgetPwdFragment;// 忘记密码
    private CheckBox mCbPassword;// 密码是否明文显示
    private InputMethodManager mImm;
    private AlertDialog mAlertDlg = null;
    private FragmentManager fm;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //super.onCreateView(inflater, container, savedInstanceState);
        View v = inflater.inflate(R.layout.fragment_login, null);
        mAlertDlg = new AlertDialog.Builder(getActivity()).create();
        fm = getActivity().getSupportFragmentManager();
        mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        initView(v);
        initData();
        return v;
    }

    public void initView(View v) {
        //  ((TextView) v.findViewById(R.id.acitivity_name)).setText(R.string.app_login);
        mBtnLogin = (Button) v.findViewById(R.id.btn_login);
        mTvRegister = (TextView) v.findViewById(R.id.btn_reg);
        mEtUsername = (EditText) v.findViewById(R.id.login_username);
        mEtPassword = (EditText) v.findViewById(R.id.login_password);
        mBtnForPassword = (Button) v.findViewById(R.id.btn_forgetpassword);
        mBtnMessage = (Button) v.findViewById(R.id.btn_message);
        //  mIbBack = (ImageButton) v.findViewById(R.id.btn_back);
        mCbPassword = (CheckBox) v.findViewById(R.id.password_checkbox);
        String mUsername = getApplication().getProperty(AppConfig.LOGIN_USERNAME);
        if (!StringUtils.isEmpty(mUsername)) {
            mEtUsername.setText(mUsername);
        }
        mBtnLogin.setOnClickListener(listener);
        mBtnForPassword.setOnClickListener(listener);
        mTvRegister.setOnClickListener(listener);
        mBtnMessage.setOnClickListener(listener);
        //mIbBack.setOnClickListener(listener);
        mCbPassword.setOnCheckedChangeListener(changeListener);
        // 打开软键盘
        mImm.showSoftInput(mEtUsername, InputMethodManager.RESULT_SHOWN);
        mImm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction fragmentTransaction = fm.beginTransaction();
//            fragmentTransaction.setCustomAnimations(
//                    R.anim.slide_right_enter,  R.anim.slide_right_enter,
//                    R.anim.slide_right_enter, R.anim.slide_right_enter);
            fragmentTransaction.setCustomAnimations(R.anim.slide_right_enter, R.anim.slide_left_exit);
            switch (v.getId()) {
                case R.id.btn_login:
                    mUsername = mEtUsername.getText().toString().trim();
                    mPassword = mEtPassword.getText().toString().trim();
                    if (StringUtils.isEmpty(mUsername)) {
                        ((BaseActivity) getActivity()).errorPrompt(mEtUsername, R.string.login_account_prompt);
                        return;
                    }
                    if (StringUtils.isEmpty(mPassword)) {
                        ((BaseActivity) getActivity()).errorPrompt(mEtPassword, R.string.login_password_prompt);
                        return;
                    }
                    mImm.hideSoftInputFromWindow(mEtUsername.getWindowToken(), 0);
                    mAlertDlg.show();
                    UIHelper.showLoadingDialog(mAlertDlg, getActivity(), R.string.login_dialog_loading);
                    final BmobUser bu2 = new BmobUser();
                    bu2.setUsername(mUsername);
                    bu2.setPassword(mPassword);
                    bu2.login(getActivity(), new SaveListener() {

                        @Override
                        public void onSuccess() {
                            mAlertDlg.dismiss();
                            UIHelper.ToastMessage(getActivity(), "登陆成功");
                            startActivity(new Intent(getActivity(), HDExplorerActivity.class));
                            getActivity().finish();
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            mAlertDlg.dismiss();
                            UIHelper.ToastMessage(getActivity(), "账号或密码错误");
                        }
                    });
                    // mPassword = MD5.get32MD5(mPassword);
                    new LoginAsyn().execute(mUsername, mPassword);
                    break;
                case R.id.btn_forgetpassword:// 忘记密码
                    if (mForgetPwdFragment == null) {
                        mForgetPwdFragment = new ForgetPwdFragment();
                    }
                    fragmentTransaction.hide(LoginFragment.this).add(R.id.login_frame, mForgetPwdFragment).addToBackStack(null).commit();
                    break;
                case R.id.btn_message:// 通过验证码登录
                    if (mLoginCodeFragment == null) {
                        mLoginCodeFragment = new LoginCodeFragment();
                    }
                    fragmentTransaction.hide(LoginFragment.this).add(R.id.login_frame, mLoginCodeFragment).addToBackStack(null).commit();
                    break;
                case R.id.btn_reg:
                    UIHelper.showSimpleBack(getActivity(), SimpleBackPage.REG, null);
                    break;
            }
        }
    };
    /**
     * 显示隐藏密码
     */
    private CompoundButton.OnCheckedChangeListener changeListener =
            new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                    if (isChecked) {
                        mEtPassword.setTransformationMethod(HideReturnsTransformationMethod// 显示密码
                                .getInstance());
                    } else {
                        mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    }
                    // 切换后将EditText光标置于末尾
                    CharSequence charSequence = mEtPassword.getText();
                    if (charSequence instanceof Spannable) {
                        Spannable spanText = (Spannable) charSequence;
                        Selection.setSelection(spanText, charSequence.length());
                    }
                }
            };

    private class LoginAsyn extends AsyncTask<String, Void, Serializable> {
        @Override
        protected Serializable doInBackground(String... params) {
            Serializable serializable = null;
            try {
                serializable = getApplication().loginVerify(params[0], params[1], false);
            } catch (AppException e) {
                AppException.run(e);
            }
            return serializable;
        }

        @Override
        protected void onPostExecute(Serializable result) {
            mAlertDlg.dismiss();
            if (result != null) {
                if (((Entity) result).isStatus()) {
                    UIHelper.ToastMessage(getActivity(),
                            getResources().getText(R.string.login_success).toString());
                    getActivity().sendBroadcast(new Intent(Constant.MOUDLE_ACTION_USER_CHANGE));
                    getActivity().finish();
                } else {
                    UIHelper.ToastMessage(getActivity(), ((Entity) result).message);
                }
            } else {
                executeOnLoadDataError();
            }
        }
    }

    private void executeOnLoadDataError() {
        AppException.getAppExceptionHandler().makeToast(getActivity());
    }
}
